/**
 * Copyright (c) 2020-2021 awen All rights reserved.
 *
 * https://www.awen.io
 *
 * 版权所有，侵权必究！
 */

package io.awen.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.awen.common.utils.R;
import io.awen.common.validator.ValidatorUtils;
import io.awen.common.validator.group.AddGroup;
import io.awen.modules.sys.entity.SysRoleEntity;
import io.awen.modules.sys.entity.SysUserEntity;
import io.awen.modules.sys.entity.SysUserTokenEntity;
import io.awen.modules.sys.form.SysLoginForm;
import io.awen.modules.sys.service.*;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 登录相关
 *
 * @author awen liu.wen@qq.com
 */
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;

	@Autowired
	private SysUserRoleService sysUserRoleService;

	@Autowired
	private SysRoleService sysRoleService;

	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	@PostMapping("/register")
	public R manageRegister(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, AddGroup.class);

		List<String> roleNameList = new ArrayList<>(2);
		roleNameList.add("收运单位管理员");
		roleNameList.add("收运单位超级管理员");
		List<SysRoleEntity> roleList = sysRoleService.list(
				new QueryWrapper<SysRoleEntity>().lambda()
						.in(SysRoleEntity::getRoleName, roleNameList)
		);
		List<Long> roleIdList = new ArrayList<>(roleList.size());
		for (SysRoleEntity role : roleList) {
			roleIdList.add(role.getRoleId());
		}
		user.setRoleIdList(roleIdList);

		sysUserService.saveUser(user);

		return R.ok();
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException {
//		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
//		if(!captcha){
//			return R.error("验证码不正确");
//		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
		if (roleIdList.indexOf(10L) < 0) {
			return R.error("您不是收运单位管理员");
		}

		//生成token，并保存到数据库
		SysUserTokenEntity token = sysUserTokenService.getById(user.getUserId());
		if (token == null) {
			return sysUserTokenService.createToken(user.getUserId());
		}
		else if (System.currentTimeMillis() > token.getExpireTime().getTime()) {
			return sysUserTokenService.createToken(user.getUserId());
		} else {
			return R.ok().put("token", token.getToken()).put("expire", 3600 * 12);
		}
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/driver/login")
	public Map<String, Object> driverLogin(@RequestBody SysLoginForm form)throws IOException {
		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
		if (roleIdList.indexOf(9L) < 0) {
			return R.error("您不是司机");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public R logout() {
		sysUserTokenService.logout(getUserId());
		return R.ok();
	}
	
}
